package com.algernoon.springmail.mail.service.impl;

import java.nio.charset.Charset;

import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.algernoon.springmail.mail.entity.Email;
import com.algernoon.springmail.mail.service.ISendEmailService;

@Service
public class SendEmailServiceImpl implements ISendEmailService {

	private Logger logger = LoggerFactory.getLogger(SendEmailServiceImpl.class);
	
	@Autowired
	private JavaMailSender javaMailSender;
	
	@Override
	public void sendEmail(Email email) {
		
		MimeMessage message = javaMailSender.createMimeMessage();
		try {
			MimeMessageHelper helper = new MimeMessageHelper(message, true, Charset.forName("UTF-8").toString());
			helper.setFrom(email.getSender());
			helper.setTo(email.getReceiver());
			helper.setSubject(email.getSubject());
			helper.setText(email.getContent(), true);
			javaMailSender.send(message);
			
			logger.info("send email success. message: {}", message.toString());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
}
